<%@page language="java"
	import="java.sql.PreparedStatement,java.sql.ResultSet"
	pageEncoding="UTF-8"%>

<!DOCTYPE>
<html>
<head>
<title>会员注册</title>
<style>
.main {
	width: 800px;
	height: 300px;
	border: 1px red solid;
	margin: 0px auto;
}

form {
	margin-top: 70px;
	margin-left: 240px;
	line-height: 30px;
}
</style>
</head>

<body>
	<%@ include file="header.jsp"%>
	<%@ include file="conn.jsp"%>
	<!-- 得到连接对象 -->
	<div class="main">
		<!-- 注册页面主体 -->
		<form method="post" onsubmit="return check()" name="registerForm">
			会员名称：<input type="text" name="username">*<br /> 会员真名：<input
				type="text" name="realname"><br /> 会员密码：<input
				type="password" name="password"><br /> 电话号码：<input
				type="text" name="mobile"><br /> 年&nbsp;&nbsp;龄：<input
				type="text" name="age">*<br /> <input type="submit"
				value="注册" />
		</form>
	</div>
	<%@ include file="footer.jsp"%>
	<script>
		function check() {
			if (registerForm.username.value == "") {
				alert("用户名必须输入！");
				registerForm.username.focus(); //获得焦点
				return false; //验证出错误时
			}
			if (registerForm.age.value == "") {
				alert("年龄必须输入！");
				registerForm.age.focus(); //获得焦点
				return false;
			}
			return true; //未验证出错误时
		}
	</script>
</body>
</html>
<%--以下为前台数据传送到数据库的代码 --%>
<%
	request.setCharacterEncoding("UTF-8"); //设置表单请求编码，避免写入数据库后出现中文乱码
	String un = request.getParameter("username");
	String pw = request.getParameter("password");
	String rn = request.getParameter("realname");
	String tel = request.getParameter("mobile");
	if (null != un) { //处理空值null
		int age = Integer.valueOf(request.getParameter("age"));
		String sql;
		PreparedStatement pst;
		sql = "select * from user where username=?";
		pst = conn.prepareStatement(sql);
		pst.setString(1, un);
		ResultSet rs = pst.executeQuery();
		if (rs.next()) {
			out.print("<script>alert('该用户名已经注册!');location.href='index.jsp'</script>");
		} else {
			//写入数据库user表
			sql = "insert into user (username,password,realname,mobile,age) values(?,?,?,?,?)";
			pst = conn.prepareStatement(sql);
			pst.setString(1, un);
			pst.setString(2, pw);
			pst.setString(3, rn);
			pst.setString(4, tel);
			pst.setInt(5, age);
			pst.executeUpdate(); //参数式操作查询				
			out.print("<script>alert('注册成功!');location.href='index.jsp'</script>");
		}
	}
%>
